package com.yc.fav.servlet;

import com.yc.fav.entity.Fav;
import com.yc.fav.entity.User;
import com.yc.fav.service.BizException;
import com.yc.fav.service.impl.FavServiceImpl;
import com.yc.fav.util.Utils;
import com.yc.fav.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/10/31
 * Email haijunzhou@hnit.edu.cn
 */
@WebServlet("/addFav")
public class AddFavServlet extends HttpServlet {

    FavServiceImpl biz = new FavServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收参数, 封装 fav 对象
        Fav fav = new Fav();
        fav.setName(req.getParameter("name"));
        fav.setAddr(req.getParameter("addr"));
        fav.setIntro(req.getParameter("intro"));
        fav.setImage(req.getParameter("image"));
        fav.setTags(req.getParameter("tags"));

        Result result = null;
        // 获取会话中用户的 id, 设置到 fav.uid
        User myinfo = (User) req.getSession().getAttribute("myinfo");
        if(myinfo == null){
            result = new Result(-6, "未登录系统,不能收藏链接", null);
        } else {
            fav.setUid(myinfo.getId());
            // 调用业务层方法
            // 捕获异常, 输出结果
            try {
                biz.create(fav);
                result = new Result(1,"链接添加成功",fav);
            } catch (BizException e) {
                result = new Result(e.getCode(),e.getMessage(),null);
            }
        }

        Utils.output(resp, result);

    }
}
